<!--
 * @Descripttion: 文件说明
 * @version: V1.0
 * @Author: GW
 * @Date: 2021-11-23 14:09:52
 * @LastEditors: GW
 * @LastEditTime: 2022-01-18 11:03:14
-->
<template>
    <a-drawer wrapClassName="crm-drawer-wrapper" :headerStyle="headerStyle" :wrapStyle="wrapStyle" placement="right" :destroyOnClose="true" :width="width" :mask="false" :visible="visible" :after-visible-change="afterVisibleChange" @close="onClose">
        <div class="big-main-wrapper">
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                         <a-col :span="4" v-show="showBtns">
                            <div class="btns" @click="onLinkManShow" >
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">添加联系人</div>
                            </div>
                        </a-col>
                        <a-col :span="4" v-show="showBtns">
                            <div class="btns" @click="importDataFun">
                                <a-icon class="btns-icon" type="import" />
                                <div class="btns-text">导入联系人</div>
                            </div>
                        </a-col>
                        <a-col :span="4">
                            <div class="btns" @click="initPage">
                                <a-icon class="btns-icon" type="file-sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                        <a-col :span="4" v-show="showBtns">
                            <div class="btns" @click="batchDeleteDetail">
                                <a-icon class="btns-icon" type="delete" />
                                <div class="btns-text">移除</div>
                            </div>
                        </a-col>
                        
                    </a-col>
                </a-row>
            </div>
           <!-- 任务明细 table -->
            <a-table :columns="columns" v-show="detailTableShow" :data-source="data" bordered :scroll="{ x: 1000, y: 400}" :pagination="false" :row-selection="rowSelection" @change="onTableChange" >
               
            </a-table>
            <!-- 选择联系人 -->
            <drag-modal title="请选择联系人" :visible="linkManModalVisible" @cancel="onLinkMancClose" width="1000px" >
                <div>
                    <!-- 选择联系人-查询条件 -->
                    <!-- <a-input-search placeholder="请选择" v-model="linkManSearchKeyWord"  @search="pageNotTaskingLinkMan" @pressEnter="pageNotTaskingLinkMan" /> -->
                    <!-- 查询方案 -->
                    <a-col :span="24" style="float: inherit;">
                        <div class="search-btn-box-gw">
                            <div class="item-small" ref="planLi">
                                <ul>
                                    <li class="item-plan" :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                                    <li class="item-plan" :title="item.searchName" :class="item.id == planActive?'active':''" v-for="(item,index) in userSearchList" :key="index" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                                    <li class="item-plan" @click="onShowSerch">
                                        自定查询
                                        <a-icon class="icon-searh-btn" type="search" />
                                    </li>
                                </ul>
                            </div>
                            <div class="item-small-down" v-if="showDownPlan" @click="showDownPlanFun">
                                <a-icon v-if="iconDirection" type="down" />
                                <a-icon v-else type="up" />
                            </div>
                        </div>
                    </a-col>
                    <!-- 查询方案结束 -->
                    <!-- 查询方案弹窗 -->
                    <a-modal class="search-wrapper-box-crm" :visible="visibleSearchPlan" title="查询" @cancel="cancel" width="800px">
                        <div class="content-box">
                            <div class="left-box">
                                <a-row class="btn-wrapper">
                                    <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                        <div class="btns" @click="planActive != 0?UserSearchSave():''">
                                            <a-icon class="btns-icon" type="save" />
                                            <div class="btns-text">保存</div>
                                        </div>
                                    </a-col>
                                    <a-col :span="6">
                                        <div class="btns" @click="showUsModal(2)">
                                            <a-icon class="btns-icon" type="save" />
                                            <div class="btns-text">另存</div>
                                        </div>
                                    </a-col>
                                    <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                        <div class="btns" @click="planActive != 0?showUsModal(1):''">
                                            <a-icon class="btns-icon" type="edit" />
                                            <div class="btns-text">修改</div>
                                        </div>
                                    </a-col>
                                    <a-col :class="planActive != 0?'':'btns-disable'" :span="6">
                                        <div class="btns" @click="planActive != 0?onUserSearchDelete({key:planActive}):''">
                                            <a-icon class="btns-icon" type="delete" />
                                            <div class="btns-text">删除</div>
                                        </div>
                                    </a-col>
                                </a-row>
                                <div class="plan-list">
                                    <ul>
                                        <li :class="planActive == 0?'active':''" @click="onUserSearchChange()">所有</li>
                                        <li v-for="(item,index) in userSearchList" :key="index" :class="item.id == planActive?'active':''" @click="onUserSearchChange(item.id)">{{item.searchName}}</li>
                                    </ul>
                                </div>
                            </div>
                            <div class="right-box">
                                <a-tabs default-activeKey="1">
                                    <a-tab-pane key="1" tab="查询条件">
                                        <dynamic-condition v-if="visibleSearchPlan" :checkable="true" :conditions="conditions" :show="true" :userSearchList="userSearchList" :userSearchSelect="userSearchSelect" :onUserSearchChange="onUserSearchChange" :onUserSearchDelete="onUserSearchDelete" rightStyle="width:150px;" rangDaterightStyle="min-width:150px;max-width:calc(410px + 0.25rem);"></dynamic-condition>
                                    </a-tab-pane>
                                </a-tabs>
                            </div>
                        </div>
                        <template slot="footer">
                            <div>
                                <!-- <div style="float:left">
                                    <a-checkbox :checked="planActive == defaultPlanActive?true:false" @change="inPagePlanSave">
                                        下次以此方案进入
                                    </a-checkbox>
                                </div> -->
                                <a-button type="primary" @click="onSerch">查询</a-button>
                                <a-button @click="cancel" class="margin-left-10">取消</a-button>
                            </div>
                        </template>
                        <a-modal :title="nowPlanType==1?'保存为另一个方案':'修改方案标题'" :visible="saveASVisible" width="400px" centered @cancel="saveAsPlanClose">
                            <a-input v-model="saveAsName" placeholder="请输入查询方案名称"></a-input>
                            <template slot="footer">
                                <div>
                                    <a-button type="primary" @click="saveAsPlanSubmit(1)">确定</a-button>
                                    <a-button @click="saveAsPlanClose" class="margin-left-10">取消</a-button>
                                </div>
                            </template>
                        </a-modal>
                    </a-modal>
                    <!-- 选择联系人-table -->
                    <div class="form-search-wrapper" style="min-height:200px;">
                        <a-table :scroll="{ x: 500, y: 500 }" :columns="linkManColumns" :data-source="linkManData" :row-selection="{ selectedRowKeys: selectedLinkManKeys, onChange: onSelectLinkManChange }" bordered :pagination="pagination" :loading="loading">

                        </a-table>
                    </div>
                </div>
                <template slot="footer">
                    <a-button type="primary" @click="addCallTaskDetail">确定</a-button>
                </template>
            </drag-modal>
            <!-- 线索客户 导入 -->
            <importAndExport ref="importRef" importType="task" :source="source" :companyType="companyType" :templateName="templateName"  :pagination="pagination" 
            :postData="{}" :onOffDefineFields="[]" :selectedKeys="[]" :exportSelectData="exportSelectData" 
            :dataSourceName="dataSourceName" @syncFun="importDataAfterFun"></importAndExport>
        </div>    
        <!-- 常用查询名称编辑框 -->
        <a-modal title="保存常用查询" :visible="UsVisible" @ok="UserSearchSave" @cancel="hideUsModal">
            <nly-row class="form-inline">
                <form-input title="名称" rightStyle="flex-grow:1;" class="ml-1 mb-1" style="flex:0.8;" :error="myUsErrors['userSearchEditItem.searchName']" :required="true" v-model="userSearchEditItem.searchName"></form-input>
            </nly-row>
        </a-modal>
        

        <template slot="title">
            <div class="crm-drawer-title clearfix">
                <div class="item-one">
                    <a-icon type="solution" /> 任务名称：{{dataItem.taskName}}  
                </div>
                <div class="item-one">
                    <a-icon type="phone" /> 外呼方式：{{dataItem.callType == 2 ? "去电放音":"人工"}}
                </div>
                <div class="item-one">
                    <a-icon type="message" /> 联系类型：{{taskTypeStr}}
                </div>
                <!-- <div class="right-box" v-show="!isFinance">
                    <a-dropdown>
                        <a-menu slot="overlay" @click="handleMenuClick">
                            <a-menu-item key="6" @click="receive">
                                <a-icon type="tags" />领用
                            </a-menu-item>
                        </a-menu>
                        <a-icon type="ellipsis" style="font-size:36px;cursor: pointer;" />
                    </a-dropdown>
                </div> -->
            </div>
        </template>
        <!-- <div v-if="loading" style="position:absolute;top:76px;left:0;bottom:0;right:0;width:100%;height:100%;background:rgba(0,0,0,0.8);z-index:201">
            <a-spin class="loading-drawer" tip="加载中..." />
        </div> -->
    </a-drawer>
</template>

<script>
import { mapState } from "vuex";
import getDate from "@/utils/tool/date";
import { clearValue, clearKeys } from "@/utils/tool/object";
import { FormInput, EditableCell } from "@/components/Form";
import importAndExport from "@/components/ImportAndExport/fileClient";
import { pageNotTaskingLinkMan } from "@/api/crm/linkMan";
import { DefineFieldList } from "@/api/crm/set";
import { list as listTaskDetail,addCallTaskDetail,batchDelete as batchDeleteDetail } from "@/api/crm/call/callTaskDetail";
import { initValidator, checkAll, checkNew } from "@/utils/validator/validator";
import { UserSearchDetail, UserSearchSave, UserSearchDelete } from "@/api/crm/userSearch";
import { PageList } from "@/api/crm/customer";
import { deepCopy } from "@/utils/tool/object";
import { DynamicCondition } from "@/components/DynamicCondition";

export default {
    components: {
        FormInput,
        EditableCell,
        importAndExport,
        DynamicCondition
    },
    props: {
        drawerVisible: {
            type: Boolean,
            default: false,
        },
        title: {
            type: String,
            default: '任务名称'
        },
        dataItem: {
            type: Object,
            default: {}
        },
    },
 
    data () {
        let crmTypeArr = ["线索客户","潜在客户","服务中客户"];
        //额外 的查询条件
        let joinTableConditions = [
            {
                "parentCode": "linkman_name",
                "sysName": "联系人.姓名",
                "name": "联系人.姓名",
                "type": "文本",
                "val": "",
                "dataType": 3,
                "sort": 1,
                "onOff": true,
                "onEdit": false,
                "onFill": true,
                "isSearch": true,
                "onLocked": true,
            },
            {
                "parentCode": "linkman_mobile",
                "sysName": "联系人.手机",
                "name": "联系人.手机",
                "type": "文本",
                "dataType": 3,
                "val": "",
                "sort": 1,
                "onOff": true,
                "onEdit": false,
                "onFill": true,
                "isSearch": true,
                "onLocked": true,
            }
        ];
        let moreCrmConditions =[
            {
                "sysName": "客户类型",
                "name": "客户类型",
                "code": "crmType",
                "source": "crm",
                "type": "下拉选择",
                "val": '[{"key":0,"title":"线索客户"},{"key":1,"title":"潜在客户"},{"key":2,"title":"服务中客户"}]',
                "length": "250",
                "sort": 1,
                "dataType": 1,
                "status": 1,
                "onOff": true,
                "onAppOff": true,
                "onEdit": false,
                "onFill": true,
                "onAppFill": true,
                "onExport": false,
                "isSearch": true,
                "isAppSearch": true,
                "onLocked": true,
                "columnWidth": 130,
            }
        ]
        //应答状态 0：// 呼出 ，对方未振铃，可能是空号 1:// 呼出 ，对方未接听2：//接通3：// 呼入，未接来电
        //任务明细表头
        const columns = [
             {
                align: "center",
                title: "序号",
                dataIndex: "index",
                width: 50,
                customRender: (text, row, index) => {
                    return index + 1;
                }
            },
             {
                align: "center",
                title: "姓名",
                dataIndex: "linkManName",
                width: 80
            },
            {
                align: "left",
                title: "客户名称",
                dataIndex: "crmName",
                width: 200,
                scopedSlots: { customRender: 'crmName' },
            },
            {
                align: "center",
                title: "移动电话",
                dataIndex: "mobile",
                width: 120,
                scopedSlots: { customRender: 'mobile' },
            },
            {
                align: "center",
                title: "呼叫次数",
                dataIndex: "callCount",
                width: 80,
            },
            {
                align: "center",
                title: "接通次数",
                dataIndex: "connectCount",
                width: 80,
            },
             {
                align: "center",
                title: "总通话时长(秒)",
                dataIndex: "totalTalkTime",
                width: 80,
            },
            {
                align: "center",
                title: "拨打状态",
                dataIndex: "lastCallStatus",
                width: 80,
                 customRender: (text, row, index) => {
                    const callStatus = text ? <sapn style="color: green">已拨打</sapn>: <sapn style="color: red">未拨打</sapn> ;
                    return callStatus;
                }
            },
            {
                align: "center",
                title: "接通状态",
                dataIndex: "lastCallResult",
                width: 80,
                 customRender: (text, row, index) => {
                     return  text ? <sapn style="color: green">已接通</sapn>: <sapn style="color: red">未接通</sapn> ; 
                }
            },
        ];
        //联系人 表头
        const linkManColumns = [
            {
                align: "left",
                title: "姓名",
                dataIndex: "linkman_name",
                width: 120
            },
            {
                title: "手机",
                dataIndex: "linkman_mobile",
                width: 120,
            },
            {
                align: "left",
                title: "客户名称",
                dataIndex: "crmName",
                width: 200,
            },
            {
                title: "客户类型",
                dataIndex: "crmType",
                width: 120,
                customRender: (text, row, index) => {
                    return crmTypeArr[text];
                }
            },
            {
                align: "center",
                title: "客户来源",
                dataIndex: "crmSource",
                width: 100,
            },
            {
                align: "center",
                title: "最新跟进记录",
                dataIndex: "lastTouchSummary",
                width: 100,
            },
             {
                align: "center",
                title: "最后联系时间",
                dataIndex: "lastTouchDate",
                width: 100,
            },
            {
                align: "center",
                title: "领用人",
                dataIndex: "collarUserName",
                width: 100,
            },
            {
                align: "center",
                title: "上次领用人",
                dataIndex: "lastCollarUserName",
                width: 100,
            },
            {
                align: "center",
                title: "创建人",
                dataIndex: "createUserName",
                width: 100,
            },
            {
                align: "center",
                title: "创建时间",
                dataIndex: "createDate",
                width: 100,
            },

          
        ];
        let typeArr = ["销售联系", "客户关怀","售后回访","投诉回访","服务支持","维修维护","客户投诉"];
        return {
            typeArr,
            visible: false,
            width: 800,
            headerStyle: {
                'background': '#00a0e9',
                'border-radius': 0,
            },
            wrapStyle: {
                'margin-top': '84px',
                'height': '720px',
            },
            columns,
            detailPostData:{
                
            },
            data:[],            //任务明细数据
            selectedKeys: [],   //任务明细table选中key
            detailTableShow:    true,
            showBtns: true,      //
            //联系人 查询方案
            visibleSearchPlan: false,   //是否显示 查询方案 弹窗
            planActive: 0,              //当前选择的查询方案id
            //选择联系人
            pagination: {
                defaultPageSize: 20,
                size: "small",
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changeLinkMamPageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    console.log("联系人：",page,pageSize);
                    this.pagination.current = page;
                    this.pagination.pageSize = pageSize;
                    Object.assign(this.postData, {
                        page:{
                            size: pageSize,
                            current: page,
                        }
                    });
                    this.PageList();
                },
                showQuickJumper: true,
                showLessItems: true
            },
            linkManModalVisible: false,
            linkManSearchKeyWord: "",
            linkManData:[],
            isLoadingSearching: false,
            linkManColumns,
            selectedLinkManKeys:[],
            selectedLinkManData:[],
            linkPostData:{
                page:{
                    "current": 1,
                    "size": 20
                },
            },
            //客户导入 
            searchType: 6,     //0:线索客户 1.潜在客户 2.成交客户  3.联系人 4.联系人记录  5.商机 6.外呼任务 选择
            source: "crm",
            crmType: 0,        //客户大类 0:线索客户  1.潜在客户 2.成交客户     
            onOffDefineFields:[],
            conditions: [], //启用 且 搜索的自定义
            companyType: "isCustomer",    //往来单位 分类 （客户：isCustomer，供应商：isSupplier,其他：isOther）
            templateName: "客户档案导入模板.xls",
            dataSourceName:'客户档案',                      //导入/导出名称
            exportSelectData:{exportValue:0}, // 要导出选中的数量
            //常用查询条件
            userSearchList: [],            //常用查询条件集合(当前所有)
            userSearchEditItem: {},        //常用查询 编辑的Item
            userSearchSelectItem: {},      //常用查询 选中的Item  
            userSearchSelect: "",          //常用查询选择的key
            UsRules: {
                "userSearchEditItem.searchName": { test: 'required' }
            },                            //常用查询 验证规则
            UsErrors: {},                 //常用查询 验证错误信息
            UsVisible: false,             //常用查询 编辑框是否显示
            basePostData: {},
            postData: {},
            joinBusinessType: 1,
            joinTableConditions, 
            moreCrmConditions,           
        };
    },
    created(){
           const { joinBusinessType,joinTableConditions } = this;
        this.GetCustomizeList();
        this.UserSearchDetail();
        this.basePostData = {
            joinTableConditions,
            joinBusinessType,
            page: {
                current: 1,
                size: 20
            },
            dtos: []
        };
        this.postData = deepCopy(this.basePostData, true);
    },
    mounted(){
        const { UsErrors, UsRules } = this;
        let vm = this;
        initValidator(vm, UsRules, UsErrors);
        console.log("常用查询 验证initValidator后", vm)
        console.log("抽屉mounted----------------------->",this.dataItem);
    },
    watch: {
        drawerVisible (val) {
            this.visible = val;
        },
        dataItem (item) {
            console.log("watch->dataItem",item);
            this.visible = true;
            this.taskId = item.id;
            this.showBtns = !item.businessStatus;
            this.initPage();
        },
        
        
    },
    computed:{
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
        myUsErrors: function () {
            return this.UsErrors
        },
        taskTypeStr:function(){
            let {dataItem,typeArr}= this;
            let result = "";
            if(dataItem.taskType){
                return typeArr[dataItem.taskType - 1];
            }
            return result;
        },
        rowSelection() {
            let { userInfo } = this;
            return {
                columnWidth:30,
                selectedRowKeys:this.selectedKeys,
                onChange: this.userSelection,
                getCheckboxProps: record => ({
                    props: {
                        disabled: userInfo.id != record.createUserId || record.callCount > 0, 
                    },
                }),
            };
        },
    },
    methods: {
         initPage(){
            this.listTaskDetail();
        },
        // 打开弹窗
        showDrawer () {
            this.visible = true;
        },
        // 关闭弹窗
        onClose () {
            this.visible = false;
            this.$emit("update:drawerVisible", false)
        },
        // 表格方法
        onTableChange(){

        },
        userSelection (keys, rows) {
            this.selectedKeys = [];
            this.selectedKeys = keys;
            console.log("rowKeys", this.selectedKeys);
        },
        //获取任务明细列表
        listTaskDetail () {
            const { detailPostData,taskId } = this;
            Object.assign(detailPostData,{taskId})
            listTaskDetail(detailPostData).then(response => {
                console.log("获取外呼任务明细列表", response);
                if (response.code === 200) {
                    const { data } = response;
                    this.data = data;
                    this.data.forEach(item => {
                        item.key = item.id;
                    });
                    this.detailTableShow = false;
                    this.$nextTick(()=>{
                        this.detailTableShow = true;
                    })
                }
            })
            .catch(error => { });
        },
        //批量删除 任务明细
        batchDeleteDetail () {
            let { taskId } = this;
            let _this = this;
            if (this.selectedKeys.length < 1) {
                this.$message.warning('请选择记录');
                return;
            }
            let ids = this.selectedKeys.join(",");
             this.$confirm({
                title: '确认',
                content: <span>您确定要{<span style='color:red;'>删除</span>}这些记录吗？</span>,
                onOk () {
                     batchDeleteDetail({taskId,ids}).then(response => {
                        if (response.code == 200) {
                            _this.selectedKeys = [];
                            _this.$message.success("删除成功");
                            //刷新 列表
                            _this.listTaskDetail();
                            _this.$emit("reload");
                        }
                    });
                },
                onCancel () { },
            });
           
        },
       

        /*--------------联系人-------------------*/
        onLinkManShow(){
            const {taskId} = this;
            if(!taskId)return;
            this.linkManModalVisible = true;
            this.PageList();
            // this.pageNotTaskingLinkMan();
        },
        onLinkMancClose(){
            this.linkManModalVisible = false;
        },
        changeLinkMamPageSize (e) {
            const value = e.target.value;
            Object.assign(this.postData, {
                page:{
                    size: value,
                    current: 1,
                }
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value),
                current: 1,
            });
            this.PageList();
        },
        onSelectLinkManChange(keys, rows){
            this.selectedLinkManKeys = keys;
            this.selectedLinkManData = rows;
        },
        //查询 可以添加任务的 联系人
        pageNotTaskingLinkMan(){
            const { linkManSearchKeyWord,linkPostData,taskId } = this;
            Object.assign(linkPostData,{
                taskId,
                keyWord:linkManSearchKeyWord
            })
            this.isLoadingSearching = true;
            pageNotTaskingLinkMan(linkPostData).then(response => {
                console.log("获取外呼任务明细列表", response);
                if (response.code === 200) {
                    this.isLoadingSearching = false;
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.linkManData = records;
                    this.linkManData.forEach(item => {
                        item.key = item.id;
                    });
                    let page = {
                        total: total,
                        pageSize: size,
                        current: current,
                    }
                    Object.assign(this.linkPagination, page);
                }
            })
            .catch(error => { this.isLoadingSearching = false;});

        },
        //从 现有客户中  添加 联系人 到任务明细
        addCallTaskDetail(){
            const { selectedLinkManData, taskId } = this;
            if(selectedLinkManData.length == 0)this.$message.warning("请选择联系人");
            selectedLinkManData.forEach(item=>{
                item.linkManId = item.id;
                item.linkManName = item.linkman_name;
                item.mobile = item.linkman_mobile;
                delete item.id;
            });
            let postData = {
                taskId,
                crmCallTaskDetailList: selectedLinkManData
            }
            addCallTaskDetail(postData).then(response=>{
                if (response.code === 200) {
                    this.$message.success("保存成功")
                    //刷新 列表
                    this.selectedLinkManKeys = [];
                    this.selectedLinkManData = [];
                    this.listTaskDetail();
                    this.onLinkMancClose();
                    this.$emit("reload");
                }
            });

        },
        /*--------------导入-------------------*/
        //导入
        importDataFun () {
            let { taskId } = this;
            if(!taskId)return;
            //导入数据
            let data = {
                moreFormData:{
                    taskId,
                    isTask:true
                }
            }
            this.$refs.importRef.importFile(data);
        },
        //导入之后回调
        importDataAfterFun(){
            this.listTaskDetail();
            this.$emit("reload");
        },

         /*--------------  客户联系人 查询条件-------------------*/
         onSerch () {
            const { postData } = this;
            postData.page.current = 1;
            this.PageList();
            this.cancel();
        },
         // 获取客户列表
        PageList () {
            this.selectedLinkManKeys = [];
            const { postData, onOffDefineFields,taskId,joinTableConditions } = this;
            console.log("外呼任务 查询客户联系人 ——搜索条件：", JSON.stringify(onOffDefineFields));
            postData.taskId = taskId;
            postData.dtos = onOffDefineFields;
            postData.joinTableConditions = joinTableConditions;
            postData.page.size = this.pagination.pageSize;
            this.loading = true;
            PageList(postData).then(response => {
                this.loading = false;
                console.log("外呼任务 查询客户联系人 response", response);
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.linkManData = records;
                    Object.assign(this.pagination, {
                        total
                    });
                }
            }).catch(error => {
                this.loading = false;
            });
        },
        //1...获取自定义字段配置 
        GetCustomizeList () {
            let { source,moreCrmConditions,joinTableConditions } = this;
            const postData = {
                source
            };
            DefineFieldList(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    let onOffDefineFields = [];
                    let conditions = [];
                    onOffDefineFields.push(...moreCrmConditions);
                    onOffDefineFields.push(...data.filter(f => f.onOff ));
                    conditions.push(...joinTableConditions);
                    conditions.push(...onOffDefineFields.filter(f => f.isSearch));
                    this.onOffDefineFields = onOffDefineFields;
                    this.conditions = conditions;
                }
            }).catch(error => { });
        },
        cancel () {
            this.visibleSearchPlan = false;
        },
        onShowSerch () {
            this.visibleSearchPlan = true;
        },
           //初始化 动态条件
        initConditions () {
            const { userSearchSelectItem, conditions } = this;
            const { searchVal } = userSearchSelectItem;
            this.postData = deepCopy(this.basePostData, true);
            if (!searchVal) return false;
            let searchValObj = JSON.parse(searchVal);
            console.log("searchValObj", searchValObj)

            conditions.forEach((f, index) => {
                delete f.value;
                delete f.rangDateVal;
                let code = f.code;
                if (f.dataType == 3 || f.dataType == 4) {
                    code = f.parentCode;
                }
                let value = searchValObj[code];
                // console.log("code",code,"value",value)
                if (value) {
                    if (f.type == "时间" || f.type == "日期") {
                        let arr = [...value];
                        let dateType = arr[0];
                        /***** 重新计算当前时间 *****/
                        let beginDate, endDate;
                        switch (dateType) {
                            case "今日":
                                beginDate = getDate.getToday().starttime;
                                endDate = getDate.getToday().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "昨日":
                                beginDate = getDate.getYesterday().starttime;
                                endDate = getDate.getYesterday().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本周":
                                beginDate = getDate.getCurrWeekDays().starttime;
                                endDate = getDate.getCurrWeekDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上周":
                                beginDate = getDate.getLastWeekDays().starttime;
                                endDate = getDate.getLastWeekDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本月":
                                beginDate = getDate.getCurrMonthDays().starttime;
                                endDate = getDate.getCurrMonthDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上月":
                                beginDate = getDate.getLastMonthDays().starttime;
                                endDate = getDate.getLastMonthDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本季度":
                                beginDate = getDate.getCurrQuarter().starttime;
                                endDate = getDate.getCurrQuarter().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上季度":
                                beginDate = getDate.getLastQuarter().starttime;
                                endDate = getDate.getLastQuarter().endtime;
                                arr[1] = [beginDate, endDate]; break;
                        }
                        console.log("初始化 动态条件:arr__", arr);
                        f.rangDateVal = arr;
                    }
                    // else if (f.type == "搜索选择") {
                    //     f.value = parseInt(value);
                    // } 
                    else {
                        f.value = value;
                    }
                }
                this.$set(this.conditions, index, f);
            });
        },
        //重置 动态条件
        resetConditions () {
            Object.assign(this.postData, deepCopy(this.basePostData, true));
            this.pagination.current = 1;
            const { conditions } = this;
            conditions.forEach &&
                conditions.forEach((f, index) => {
                    delete f.value;
                    delete f.rangDateVal;
                    this.$set(this.conditions, index, f);
                });
            //重置 常用查询条件选项
            Object.assign(this, {
                userSearchSelect: "",
                userSearchSelectItem: {},
                isCollected: false
            })
            console.log("this.conditions", this.conditions);
        },
        // GetCustomizeList
        //重置 
        reset () {
            //重置 动态条件
            this.resetConditions();

            console.log("重置_pagelist")
            this.PageList();
        },
         /**
         * gw 处理方案过多溢出 2021年8月28日09:11:29
         */
        showDownCheck () {
            //方案 和 外层box 宽度比较
            if (document.getElementsByClassName('item-small').length == 0) {
                //处理和其他页面同时打开,获取不到该bom报错的处理
                return;
            }
            let planWidth = document.getElementsByClassName('item-small')[0].clientWidth;
            let planList = document.getElementsByClassName('item-plan');
            let planListWidthTotal = null;
            planList.forEach(item => {
                // console.log(item.clientWidth)
                planListWidthTotal = planListWidthTotal + item.clientWidth;
            });
            planListWidthTotal = planListWidthTotal + planList.length * 5;

            // console.log('方案总长度：', planListWidthTotal, ',当前显示方案dom的宽度：', planWidth)
            if (planListWidthTotal > planWidth) {
                this.showDownPlan = true;
                this.iconDirection = true;
            } else {
                this.showDownPlan = false;
                this.iconDirection = false;
            }
        },
        showDownPlanFun () {
            let planBox = this.$refs.planLi;
            //显示更多的方案
            this.$nextTick(() => {
                if (planBox.clientHeight == 40) {
                    this.iconDirection = false;
                    planBox.style.height = 'auto';
                } else {
                    this.iconDirection = true;
                    planBox.style.height = '40px'
                }
            })
        },
        //获取用户常用查询条件
        UserSearchDetail () {
            const { searchType } = this;
            let postData = {
                searchType: searchType
            };
            UserSearchDetail(postData)
                .then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        this.userSearchList = data;

                        //重新计算是否展示方案下拉按钮
                        this.$nextTick(() => {
                            this.showDownCheck();
                        })
                    }
                })
                .catch(error => { });
        },
        //保存 用户常用查询
        UserSearchSave () {

            const { UsRules, UsErrors, userSearchEditItem, searchType, onOffDefineFields, conditions } = this;
            const { id, searchName } = userSearchEditItem;
            //全部校验一次
            checkAll(this, UsRules, userSearchEditItem, UsErrors);
            console.log("全部校验一次_userSearchEditItem", userSearchEditItem, "UsErrors", UsErrors)
            if (Object.keys(UsErrors).length > 0) {
                this.isFromShow = false;
                this.isFromShow = true;
                return false;
            }
            // 组装查询条件对象
            let searchVal = new Object();
            conditions.forEach(f => {
                let code = f.code;
                if (f.dataType == 3 || f.dataType == 4) {
                    code = f.parentCode;
                }
                if (f.value) {
                    searchVal[code] = f.value;
                } else if (f.rangDateVal) {
                    searchVal[code] = f.rangDateVal;
                }
            });
            console.log("searchVal", searchVal)
            //gw 注释2021年8月16日14:57:51
            // if (!searchVal || Object.keys(searchVal).length == 0) {
            //     this.$nlyaToast.toast("常用查询条件不能为空", {
            //         title: `错误`,
            //         variant: "danger",
            //         solid: true
            //     });
            //     return false;
            // }
            let postData = {
                id,
                searchName, //视图名称
                searchVal: JSON.stringify(searchVal),  //视图内容
                searchType  //视图类型
            };
            UserSearchSave(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success("保存成功");
                    this.hideUsModal();
                    this.UserSearchDetail();
                }
            })
                .catch(error => { });
        },
        //删除 用户常用查询条件 事件
        onUserSearchDelete (item) {
            let { userSearchList } = this;
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该记录吗？',
                onOk () {
                    UserSearchDelete({ id: item.key }).then(response => {
                        if (response.code === 200) {
                            _this.$message.success("删除成功");
                            //删除 
                            userSearchList = userSearchList.filter(f => f.id != item.key);
                            Object.assign(_this, {
                                userSearchList
                            })
                            //处理 选中的 被删除
                            if (_this.userSearchSelect == item.key) {
                                //特殊处理
                                _this.reset();
                                _this.hideUsModal();
                            }
                            _this.planActive = 0;
                            //重新计算是否展示方案下拉按钮
                            _this.$nextTick(() => {
                                _this.showDownCheck();
                            })
                        }
                    })
                },
                onCancel () {

                },
            });
        },
        //选择 用户常用查询条件 事件
        onUserSearchChange (value) {
            this.planActive = value;
            const { userSearchList, userSearchEditItem } = this;
            //如果选中了值
            if (value) {
                let intValue = parseInt(value);
                const find = userSearchList.find(f => f.id == intValue);
                if (find) {
                    Object.assign(this, {
                        userSearchSelectItem: find
                    });
                    Object.assign(this.userSearchEditItem, { ...find });
                    //赋值 动态查询条件
                    this.initConditions();
                    this.PageList();
                }
                this.userSearchSelect = intValue;
            } else {
                clearValue(userSearchEditItem);
                //清除 动态查询条件
                this.reset();
                this.planActive = 0;
            }

        },
        //打开 userSearch 弹窗
        showUsModal (type) {
            //type:2 另存 type：1 修改
            const { userSearchSelectItem, userSearchEditItem } = this;
            console.log("showUsModal_")
            Object.assign(userSearchEditItem, {
                id: type == 1 ? userSearchSelectItem.id : null,
                searchName: type == 1 ? userSearchSelectItem.searchName : null,
            })
            this.UsVisible = true;
        },
        //关闭 userSearch 弹窗
        hideUsModal () {
            const { UsErrors, userSearchEditItem } = this;
            this.UsVisible = false;
            clearValue(userSearchEditItem);
            clearValue(UsErrors);

        },
    },
}
</script>

<style lang="less" scoped>
    .crm-drawer-wrapper {
        .ant-drawer-body {
            padding: 0;
        }
        .ant-drawer-close {
            color: #fff;
        }
        .crm-drawer-title {
            color: #fff;
            vertical-align: middle;
            font-size: 16px;
            width: 100%;
            padding-right: 30px;
            .anticon {
                font-size: 22px;
            }
            .item-one {
                float: left;
                font-weight: bold;
                min-width: 200px;
                line-height: 44px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                margin-right: 10px;
            }
            .item-two {
                float: left;
                cursor: pointer;
                font-size: 14px;
            }
            .heart-yes {
                color: #ff4d4f;
            }
            .heart-no {
                color: #ccc;
            }
        }

        .ant-tabs-bar {
            margin-bottom: 0px;
        }

        .right-box {
            float: right;
            width: 44px;
            height: 43px;
            line-height: 51px;
        }
    }
    .loading-drawer {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-top: -100px;
        margin-left: -30px;
        font-size: 14px;
        color: #fff;
        .ant-spin-dot {
            font-size: 60px;
        }
        .ant-spin-dot i {
            width: 30px;
            height: 30px;
            background: #fff;
        }
    }

    /** 查询条件*/
    .search-wrapper-box-crm {
        .ant-modal-close {
            z-index: 1;
        }

        .ant-modal-body {
            padding: 0 !important;
        }

        .content-box {
            display: flex;
            height: 450px;

            .left-box {
            padding: 5px 0;
            flex: 0 0 200px;
            height: 100%;
            border-right: 1px solid #ccc;

            .plan-list {
                height: calc(100% - 45px);
                overflow-y: auto;
            }

            .plan-list ul {
                margin: 0;
                padding: 0;
            }

            .plan-list ul>li {
                list-style: none;
                width: 100%;
                padding-left: 10px;
                line-height: 32px;
                border-bottom: 1px solid #ccc;
                cursor: pointer;

                &.active {
                background-color: #3788ff;
                color: #fff;
                }
            }

            .plan-list ul>li:hover {
                background-color: rgba(55, 136, 255, 0.2);
                color: #666;
            }

            .plan-list ul>li:last-child {
                border-bottom: none;
            }
            }

            .right-box {
            padding: 2px 0;
            flex: 1;
            height: 100%;
            overflow-y: auto;

            .condition {
                padding: 0 10px;
                margin-bottom: 10px;
                overflow-y: auto;

                .filter {
                display: table;
                margin-top: 10px;

                .filter-label {
                    display: table-cell;
                    font-weight: normal;
                    max-width: 160px;
                    white-space: nowrap;
                    vertical-align: bottom;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }

                .filter-control {
                    display: table-cell;
                    width: 100%;
                }

                .ant-select-selection--single {
                    height: auto;
                }

                .ant-input-number {
                    width: auto;
                }

                .ant-input,
                .ant-input-number,
                .ant-select-selection {
                    border-radius: 0;
                    border: none;
                    border-bottom: 1px solid #ccc;
                }

                .ant-input-number,
                .ant-select-selection,
                .ant-calendar-picker,
                .ant-calendar-picker-input,
                .ant-input:focus {
                    box-shadow: none;
                }

                .ant-input-number-handler-wrap {
                    display: none;
                }
                }
            }

            .dynamic-table-design {
                padding: 0 10px;
            }
            }

            .btn-wrapper {
            text-align: center;
            background: #fff;
            padding-top: 7px;
            border-bottom: 1px solid #a0a0a0;
            height: 48px;

            .btns {
                font-size: 12px;
                text-align: center;
                cursor: pointer;
                overflow: hidden;
            }

            .btns-ccc {
                color: #ccc;
            }

            .btns-text {
                margin-top: -2px;
                height: 20px;
                overflow: hidden;

                .anticon-down {
                color: rgb(24, 144, 255);
                vertical-align: middle;
                }
            }

            .btns-icon {
                font-size: 18px;
                color: rgb(24, 144, 255);
            }

            .btns-icon-ccc {
                color: #ccc;
            }

            .btns:hover {
                .btns-icon {
                color: rgb(45, 85, 216);
                }

                transition: all 0.2s;
            }

            .btns:active {
                animation: btns-transform 0.1s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
            }

            //按钮制灰
            .btns-disable {
                color: #7f7d7d;

                .btns-icon {
                color: #7f7d7d;
                }

                .btns:hover {
                .btns-icon {
                    color: #7f7d7d;
                }
                }

                .btns-text {
                color: #7f7d7d;

                .anticon-down {
                    color: #7f7d7d;
                }
                }
            }
            }
        }



        .mask-archives {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0);
            z-index: 2;
        }

        .mask-archives-name {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0);
            z-index: 4;
        }
    }

.search-btn-box-gw {
    display: flex;
    border-bottom: 1px solid #CCC;
    margin-top: 4px;
    // height: 40px;
    padding-left: 8px;
    width: 100%;

    .item-big {
      flex: 0 0 60px;
      font-size: 14px;
      text-align: center;
      color: #000;
      // font-weight: bold;
      line-height: 20px;
      cursor: pointer;

      .icon-searh {
        font-size: 19px;
        color: rgb(45, 144, 236);
      }
    }

    .item-small-down {
      width: 42px;
      height: 42px;
      line-height: 42px;
      text-align: center;
      cursor: pointer;
    }

    .item-small {
      width: calc(100% - 50px);
      height: 40px;

      ul {
        width: 100%;
        list-style: none;
        padding: 0;
        margin: 0;
        clear: both;
      }

      ul>li {
        float: left;
        // border: 1px solid rgb(162, 187, 203);
        color: #333;
        height: 32px;
        line-height: 32px;
        padding: 0px 10px;
        font-size: 14px;
        // margin-right: 10px;
        max-width: 110px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-right: 5px;
        margin-top: 7px;
      }

      ul>li.active {
        background: #1E9FFF;
        color: #FFFFFF;
      }

      .icon-searh-btn {
        color: #1e9fff;
      }

      ul>li:hover {
        background: #1E9FFF;
        color: #FFFFFF;

        .icon-searh-btn {
          color: #FFFFFF;
        }
      }

      .item-plan {
        cursor: pointer;
      }
    }
  }
</style>
